/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import service.Audio;
import service.Connection;
import service.Photo;
import service.PhotoCollection;
import service.Planet;
import service.PlanetFacadeREST;
import service.Tag;
import service.Universe;
import service.UniverseFacadeREST;
import service.Video;

/**
 *
 * @author andrew
 */
public class GetUniverseServlet extends HttpServlet {

    @EJB
    private UniverseFacadeREST universeManager;
    
    @EJB
    private PlanetFacadeREST planetManager;

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        System.out.println("Oh mi hanno chiamato!");
        
        String u1String = request.getParameter("u1");
        String u2String = request.getParameter("u2");
        String u3String = request.getParameter("u3");
        
        Integer u1 = (u1String != null) ? (u1 = Integer.parseInt(u1String)) : (u1 = -1);
        Integer u2 = (u2String != null) ? (u2 = Integer.parseInt(u2String)) : (u2 = -1);
        Integer u3 = (u3String != null) ? (u3 = Integer.parseInt(u3String)) : (u3 = -1);
        
        String pathFileXML = request.getServletContext().getRealPath("/") + "Universes/"+"universes.xml";
        
        ArrayList<Integer> IdUniversearray = new ArrayList<Integer>();
        
        if(u1!=-1)
            IdUniversearray.add(u1);
        if(u2!=-1)
            IdUniversearray.add(u2);
        if(u3!=-1)
            IdUniversearray.add(u3);
            
        
        writeXMLFile(IdUniversearray, pathFileXML, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void writeXMLFile(ArrayList<Integer> array, String pathXML, HttpServletResponse response) {
        
        try {
            
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            
            // root (universes) elements
            Document doc = docBuilder.newDocument();
            Element universes = doc.createElement("universes");
            doc.appendChild(universes);
            
            Iterator<Integer> arrayIt = array.iterator();
            
            while(arrayIt.hasNext()){
                Integer idUniverse = arrayIt.next();
                
                //creo elemento universe
                Universe universe = universeManager.find(idUniverse);
                
                
                // universeElement
                Element universeElement = doc.createElement("universe");
                universes.appendChild(universeElement);

                    // set attribute <id> to universe element
                    Attr attr_id_universe = doc.createAttribute("id");
                    attr_id_universe.setValue(universe.getIdUniverse().toString());
                    universeElement.setAttributeNode(attr_id_universe);

                    // set attribute <name> to universe element
                    Attr attr_name_universe = doc.createAttribute("name");
                    attr_name_universe.setValue(universe.getName());
                    universeElement.setAttributeNode(attr_name_universe);
                    
                // description in universe
                Element descriprionUniverseElement = doc.createElement("description");
                descriprionUniverseElement.appendChild(doc.createTextNode(universe.getDescription()));
                universeElement.appendChild(descriprionUniverseElement);
                         
                
                
                
                // estraggo pianeti dell'universo
                Collection<Planet> planetList = universe.getPlanetCollection();
                
                Iterator<Planet> planetIt = planetList.iterator();
                Planet planet;
                while(planetIt.hasNext()){
                    planet = planetIt.next();
                    
                    //System.out.println("Emotional filter in planet = "+planet.getEmotionalFilter());
                 
                    // --- create planetElement ---
                    Element planetElement = doc.createElement("planet");
                    universeElement.appendChild(planetElement);
                
                        // set attribute <id> to planet element
                        Attr attr_id_planet = doc.createAttribute("id");
                        attr_id_planet.setValue(planet.getIdPlanet().toString());
                        planetElement.setAttributeNode(attr_id_planet);

                        // set attribute <name> to planet element
                        Attr attr_name_planet = doc.createAttribute("name");
                        attr_name_planet.setValue(planet.getShortLabel());
                        planetElement.setAttributeNode(attr_name_planet);
                        
                    // title1 planet
                    Element title1Element = doc.createElement("title1");
                    title1Element.appendChild(doc.createTextNode(planet.getTitle1()));
                    planetElement.appendChild(title1Element);
                    
                    // title2 planet
                    Element title2Element = doc.createElement("title2");
                    title2Element.appendChild(doc.createTextNode(planet.getTitle2()));
                    planetElement.appendChild(title2Element);
                    
                    // title3 planet
                    Element title3Element = doc.createElement("title3");
                    title3Element.appendChild(doc.createTextNode(planet.getTitle3()));
                    planetElement.appendChild(title3Element);
                        
                    // description planet
                    Element descriprionPlanetElement = doc.createElement("description");
                    descriprionPlanetElement.appendChild(doc.createTextNode(planet.getDescription()));
                    planetElement.appendChild(descriprionPlanetElement);
                    
                    // TODO: conversione
                    
                    // coordX planet
                    float percY = 1-(((float)planet.getCoordinatePositionX()-100)/1197);
                    float convertedY = percY * 1984;
                    System.out.println("perc convY "+percY);
                    float percX = 1-(((float)planet.getCoordinatePositionY()-100)/470);
                    float convertedX = percX * 630;
                    System.out.println("perc convX "+percX);
                    
                    Element coordXElement = doc.createElement("coordX");
                    coordXElement.appendChild(doc.createTextNode(Float.toString(convertedY)));//planet.getCoordinatePositionX().toString()));
                    planetElement.appendChild(coordXElement);
                    
                    // coordY planet
                    Element coordYElement = doc.createElement("coordY");
                    coordYElement.appendChild(doc.createTextNode(Float.toString(convertedX)));;//planet.getCoordinatePositionY().toString()));
                    planetElement.appendChild(coordYElement);
                    
                    // create connections
                    Element connectionsElement = doc.createElement("connections");
                    planetElement.appendChild(connectionsElement);
                    
                        
                        
                            // gestione oggetto connessione
                            Collection<Connection> connList = planet.getConnectionCollection();
                            
                            Iterator<Connection> connIt = connList.iterator();
                            Connection connection = null;
                            while(connIt.hasNext()){
                                connection = connIt.next();
                                
                                // create planetId
                                Element planetIdElement = doc.createElement("planetId");
                                planetIdElement.appendChild(doc.createTextNode(Integer.valueOf(connection.getDestinationPlanet()).toString()));
                                connectionsElement.appendChild(planetIdElement);
                                
                                    // set attribute planetId - r
                                    Attr attr_planetId_r = doc.createAttribute("r");
                                    attr_planetId_r.setValue(Integer.valueOf(connection.getR()).toString());
                                    planetIdElement.setAttributeNode(attr_planetId_r);

                                    // set attribute planetId - g
                                    Attr attr_planetId_g = doc.createAttribute("g");
                                    attr_planetId_g.setValue(Integer.valueOf(connection.getG()).toString());
                                    planetIdElement.setAttributeNode(attr_planetId_g);

                                    // set attribute planetId - b
                                    Attr attr_planetId_b = doc.createAttribute("b");
                                    attr_planetId_b.setValue(Integer.valueOf(connection.getB()).toString());
                                    planetIdElement.setAttributeNode(attr_planetId_b);
                                    
                                    // set attribute planetId - iduniverse
                                    Attr attr_planetId_universe = doc.createAttribute("iduniverse");
                                    attr_planetId_universe.setValue(Integer.valueOf(universe.getIdUniverse()).toString());
                                    planetIdElement.setAttributeNode(attr_planetId_universe);
                            }
                            
                            
                            //--------------------------- TAG --------------------------------
                            
                            // prendo ID di universi in considerazione
                            Iterator<Integer> arrayIDUniverseIt = array.iterator();
                            
                            
                            // se id universo è diverso allora lo prendo in considerazione
                            while(arrayIDUniverseIt.hasNext()){
                                Integer id_universe_extra = arrayIDUniverseIt.next();
                                if(id_universe_extra != idUniverse){
                                    
                                    // prendo tutti i pianeti di questo universo
                                    Universe universe_extra = universeManager.find(id_universe_extra);
                                    Collection<Planet> planetColl = universe_extra.getPlanetCollection();
                                    
                                    // prendo ogni singolo pianeta
                                    Iterator<Planet> planet_extra_it = planetColl.iterator();
                                    Planet tmp_planet_extra;
                                    while(planet_extra_it.hasNext()){
                                        tmp_planet_extra = planet_extra_it.next();
                                        
                                        //prendo tag di quel pianeta
                                        Collection<Tag> tag_coll_extra = tmp_planet_extra.getTagCollection();
                                        Iterator<Tag> tag_coll_extra_it = tag_coll_extra.iterator();
                                        
                                        // prendo ogni tag del paineta perno e lo controllo con i tag di quello che ciclo
                                        Collection<Tag> tagColl = planet.getTagCollection();
                                        Iterator<Tag> tagIt = tagColl.iterator();
                                        
                                        
                                        Tag tmpTag;
                                        while(tagIt.hasNext()){
                                            tmpTag = tagIt.next();
                                            
                                            //scorro tag del pianeta che in considerazione
                                            while(tag_coll_extra_it.hasNext()){
                                                Tag t = tag_coll_extra_it.next();
                                                // se uguale inserisco
                                                if(t.getDescription().equalsIgnoreCase(tmpTag.getDescription())){
                                                    
                                                    // --- inserisco collegamento in XML ---
                                                    
                                                    // create planetId
                                                    Element planetIdElement = doc.createElement("planetId");
                                                    planetIdElement.appendChild(doc.createTextNode(Integer.valueOf(tmp_planet_extra.getIdPlanet()).toString()));
                                                    connectionsElement.appendChild(planetIdElement);
                                
                                                    // set attribute planetId - r
                                                    Attr attr_planetId_r = doc.createAttribute("r");
                                                    attr_planetId_r.setValue(Integer.valueOf(-1).toString());
                                                    planetIdElement.setAttributeNode(attr_planetId_r);

                                                    // set attribute planetId - g
                                                    Attr attr_planetId_g = doc.createAttribute("g");
                                                    attr_planetId_g.setValue(Integer.valueOf(-1).toString());
                                                    planetIdElement.setAttributeNode(attr_planetId_g);

                                                    // set attribute planetId - b
                                                    Attr attr_planetId_b = doc.createAttribute("b");
                                                    attr_planetId_b.setValue(Integer.valueOf(-1).toString());
                                                    planetIdElement.setAttributeNode(attr_planetId_b);

                                                    // set attribute planetId - iduniverse
                                                    Attr attr_planetId_universe = doc.createAttribute("iduniverse");
                                                    attr_planetId_universe.setValue(Integer.valueOf(universe_extra.getIdUniverse()).toString());
                                                    planetIdElement.setAttributeNode(attr_planetId_universe);
                                                    
                                                    // --- stop XML ---
                                                    
                                                    
                                                }
                                                // se non è uguale provo a fare match
                                                else{
                                                    // metto in vettore i tag
                                                    String[] currentTag = t.getDescription().split(" ");
                                                    int dim_currentTag = currentTag.length;
                                                    
                                                    String[] refTag = tmpTag.getDescription().split(" ");
                                                    int dim_refTag = refTag.length;
                                                    
                                                    int dimMin = Math.min(dim_currentTag, dim_refTag);
                                                    
                                                    String[] minVec;
                                                    String[] maxVec;
                                                    
                                                    // determino quale dei due è più corto
                                                    if(dimMin == dim_currentTag){
                                                        minVec = currentTag;
                                                        maxVec = refTag;
                                                    }else{
                                                        minVec = refTag;
                                                        maxVec = currentTag;
                                                    }
                                                    
                                                    for(int i=0; i<dimMin;i++){
                                                        //prendo elemento di vettore più corto e lo contronto
                                                        // con ogni elemento dell'altro vettore
                                                        String tmp1 = minVec[i];
                                                        
                                                        for(int j=0; j<dimMin; j++){
                                                            String tmp2 = maxVec[j];
                                                            
                                                            // controllo carattere per carattere
                                                            int count_char = 0;
                                                            // determino stringa più lunga
                                                            if(tmp1.length()>tmp2.length()){
                                                                // scorro su tmp2
                                                                for(int k=0;k<tmp2.length();k++){
                                                                    if(tmp2.charAt(k) == tmp1.charAt(k)){
                                                                        count_char++;
                                                                    }
                                                                }
                                                            }else{
                                                                // scorro su tmp1
                                                                for(int k=0;k<tmp1.length();k++){
                                                                    if(tmp1.charAt(k) == tmp2.charAt(k)){
                                                                        count_char++;
                                                                    }
                                                                }
                                                            }
                                                            
                                                            
                                                        }
                                                        // se count_char > 5 allora inserisco tag
                                                        // --- inserisco collegamento in XML ---
                                                    
                                                    // create planetId
                                                    Element planetIdElement = doc.createElement("planetId");
                                                    planetIdElement.appendChild(doc.createTextNode(Integer.valueOf(tmp_planet_extra.getIdPlanet()).toString()));
                                                    connectionsElement.appendChild(planetIdElement);
                                
                                                    // set attribute planetId - r
                                                    Attr attr_planetId_r = doc.createAttribute("r");
                                                    attr_planetId_r.setValue(Integer.valueOf(-1).toString());
                                                    planetIdElement.setAttributeNode(attr_planetId_r);

                                                    // set attribute planetId - g
                                                    Attr attr_planetId_g = doc.createAttribute("g");
                                                    attr_planetId_g.setValue(Integer.valueOf(-1).toString());
                                                    planetIdElement.setAttributeNode(attr_planetId_g);

                                                    // set attribute planetId - b
                                                    Attr attr_planetId_b = doc.createAttribute("b");
                                                    attr_planetId_b.setValue(Integer.valueOf(-1).toString());
                                                    planetIdElement.setAttributeNode(attr_planetId_b);

                                                    // set attribute planetId - iduniverse
                                                    Attr attr_planetId_universe = doc.createAttribute("iduniverse");
                                                    attr_planetId_universe.setValue(Integer.valueOf(universe_extra.getIdUniverse()).toString());
                                                    planetIdElement.setAttributeNode(attr_planetId_universe);
                                                    
                                                    // --- stop XML ---
                                                    }
                                                    
                                                }
                                            }
                                            
                                            
                                        }
                                        
                                    }
                                    
                                    
                                }
                            }
                            
                            
                            
                            
                            //----------------------FINE TAG----------------------------------
                            
                        
                            // create image_set_happy
                            Element imageSetHappyElement = doc.createElement("image_set_happy");
                            planetElement.appendChild(imageSetHappyElement);
                            
                            // create image_set_sad
                            Element imageSetSadElement = doc.createElement("image_set_sad");
                            planetElement.appendChild(imageSetSadElement);
                            
                            // prendo immagini felici
                            Collection<PhotoCollection> photoCollectionList = planet.getPhotoCollectionCollection();
                            
                            Iterator<PhotoCollection> photoCollectionIt = photoCollectionList.iterator();
                            PhotoCollection photoCollection;
                            while(photoCollectionIt.hasNext()){
                                photoCollection = photoCollectionIt.next();
                                
                                if(photoCollection.getIsHappy()){
                                    
                                    // create descriptionElement photoCollection
                                    Element descriptionHappyCollectionElement = doc.createElement("description");
                                    descriptionHappyCollectionElement.appendChild(doc.createTextNode(photoCollection.getDescription()));
                                    imageSetHappyElement.appendChild(descriptionHappyCollectionElement);
                                    
                                    if(planet.getEmotionalFilter() == 1){
                                        // inserisco descrizione in set triste se non c'è emotional filter
                                        Element descriptionSadCollectionElement = doc.createElement("description");
                                        descriptionSadCollectionElement.appendChild(doc.createTextNode(photoCollection.getDescription()));
                                        imageSetSadElement.appendChild(descriptionSadCollectionElement);
                                    }
                                    
                                    // si scorrono le immagini felici
                                    Collection<Photo> photoList = photoCollection.getPhotoCollection();
                                    
                                    Iterator<Photo> photoIt = photoList.iterator();
                                    Photo photo;
                                    while(photoIt.hasNext()){
                                        photo = photoIt.next();
                                        
                                        // create image
                                        Element imageElement = doc.createElement("image");
                                        imageElement.appendChild(doc.createTextNode(photo.getPathPhoto()));
                                        imageSetHappyElement.appendChild(imageElement);
                                    }   
                                }else if(!photoCollection.getIsHappy()){                                    
                                    // create descriptionElement photoCollection
                                    if(planet.getEmotionalFilter() == 2){
                                        Element descriptionSadCollectionElement = doc.createElement("description");
                                        descriptionSadCollectionElement.appendChild(doc.createTextNode(photoCollection.getDescription()));
                                        imageSetSadElement.appendChild(descriptionSadCollectionElement);
                                    }
                                    // si scorrono le immagini tristi
                                    Collection<Photo> photoList = photoCollection.getPhotoCollection();
                                    
                                    Iterator<Photo> photoIt = photoList.iterator();
                                    Photo photo;
                                    
                                    
                                    
                                    if(photoList.isEmpty()){
                                        
                                        // inserisco in triste le immagini felici
                                        //System.err.print("Dimensione photoList2:: is empty");
                                        Iterator<PhotoCollection> photoCollIt = photoCollectionList.iterator();
                                        PhotoCollection p;
                                        while(photoCollIt.hasNext()){
                                            p = photoCollIt.next();
                                            // si scorrono le immagini felici
                                            Collection<Photo> pL = p.getPhotoCollection();

                                            Iterator<Photo> pIt = pL.iterator();
                                            Photo photoWithoutSad;
                                            while(pIt.hasNext()){
                                                photoWithoutSad = pIt.next();

                                                // create image
                                                Element imageElement = doc.createElement("image");
                                                imageElement.appendChild(doc.createTextNode(photoWithoutSad.getPathPhoto()));
                                                imageSetSadElement.appendChild(imageElement);
                                            }  
                                        }
                                    }else{
                                        while(photoIt.hasNext()){
                                            photo = photoIt.next();

                                            // create image
                                            Element imageElement = doc.createElement("image");
                                            imageElement.appendChild(doc.createTextNode(photo.getPathPhoto()));
                                            imageSetSadElement.appendChild(imageElement);
                                        }
                                    }
                                    
                                    
                                    
                                       
                                    
                                }
                            }
                            
                            
                            
                            
                            // create multimedia_happy
                            Element multimediaHappyElement = doc.createElement("multimedia_happy");
                            planetElement.appendChild(multimediaHappyElement);
                            
                            // create multimedia_sad
                            Element multimediaSadElement = doc.createElement("multimedia_sad");
                            planetElement.appendChild(multimediaSadElement);
                            
                            // cerco se è un audio o un video e di conseguenza setto la description di multimedia_happy 
                            String descriptionMultimediaHappy = "";
                            String titleAudioHappy = "";
                            String titleVideoHappy = "";
                            String pathAudioHappy = "";
                            String pathVideoHappy = "";
                            
                            String descriptionMultimediaSad = "";
                            String titleAudioSad = "";
                            String titleVideoSad = "";
                            String pathAudioSad = "";
                            String pathVideoSad = "";
                            
                            
                            Collection<Audio> audioList = planet.getAudioCollection();
                            Iterator<Audio> audioIt = audioList.iterator();
                            Audio audio;
                            while(audioIt.hasNext()){
                                audio = audioIt.next();
                                if(audio.getIsHappy()){
                                    
                                    // allora il contenuto felice è un audio
                                    descriptionMultimediaHappy = audio.getDescription();
                                    titleAudioHappy = audio.getTitle();
                                    pathAudioHappy = audio.getPathAudio();
                                    
                                    if(planet.getEmotionalFilter() == 1){
                                        // se non c'è filtro emozionale replico i dati in sad
                                        descriptionMultimediaSad = audio.getDescription();
                                        titleAudioSad = audio.getTitle();
                                        pathAudioSad = audio.getPathAudio();
                                    }
                                    
                                }else if(!audio.getIsHappy() && (planet.getEmotionalFilter()==2)){
                                    // allora il contenuto triste è un audio
                                    descriptionMultimediaSad = audio.getDescription();
                                    titleAudioSad = audio.getTitle();
                                    pathAudioSad = audio.getPathAudio();
                                    
                                }
                            }
                            
                            Collection<Video> videoList = planet.getVideoCollection();
                            Iterator<Video> videoIt = videoList.iterator();
                            Video video;
                            while(videoIt.hasNext()){
                                video = videoIt.next();
                                if(video.getIsHappy()){
                                    
                                    // allora il contenuto felice è un video
                                    descriptionMultimediaHappy = video.getDescription();
                                    titleVideoHappy = video.getTitle();
                                    pathVideoHappy = video.getPathVideo();
                                    
                                    if(planet.getEmotionalFilter() == 1){
                                        // se non c'è filtro emozionale replico i dati in sad
                                        descriptionMultimediaSad = video.getDescription();
                                        titleVideoSad = video.getTitle();
                                        pathVideoSad = video.getPathVideo();
                                    }
                                    
                                }else if(!video.getIsHappy() && (planet.getEmotionalFilter()==2)){
                                    
                                    // allora il contenuto triste è un video
                                    descriptionMultimediaSad = video.getDescription();
                                    titleVideoSad = video.getTitle();
                                    pathVideoSad = video.getPathVideo();
                                    
                                }
                            }
                            
                            // create description multimedia_happy element
                            Element descriptionMultimediaHappyElement = doc.createElement("description");
                            descriptionMultimediaHappyElement.appendChild(doc.createTextNode(descriptionMultimediaHappy));
                            multimediaHappyElement.appendChild(descriptionMultimediaHappyElement);
                            
                            // create description multimedia_sad element
                            Element descriptionMultimediaSadElement = doc.createElement("description");
                            descriptionMultimediaSadElement.appendChild(doc.createTextNode(descriptionMultimediaSad));
                            multimediaSadElement.appendChild(descriptionMultimediaSadElement);
                            
                            
                            // create audioElement for happy content
                            Element audioHappyElement = doc.createElement("audio");
                            if(!pathAudioHappy.equals("")){
                                audioHappyElement.appendChild(doc.createTextNode(pathAudioHappy));
                            }
                            multimediaHappyElement.appendChild(audioHappyElement);
                            
                                // insert title attribute in audio happy
                                Attr attr_title_audio_happy = doc.createAttribute("title");
                                attr_title_audio_happy.setValue(titleAudioHappy);
                                audioHappyElement.setAttributeNode(attr_title_audio_happy);
                                
                                
                            // create audioElement for sad content
                            Element audioSadElement = doc.createElement("audio");
                            if(!pathAudioSad.equals("")){
                                audioSadElement.appendChild(doc.createTextNode(pathAudioSad));
                            }
                            multimediaSadElement.appendChild(audioSadElement);
                            
                                // insert title attribute in audio sad
                                Attr attr_title_audio_sad = doc.createAttribute("title");
                                attr_title_audio_sad.setValue(titleAudioSad);
                                audioSadElement.setAttributeNode(attr_title_audio_sad);
                            
                                
                            // create videoElement for happy content
                            Element videoHappyElement = doc.createElement("video");
                            if(!pathVideoHappy.equals("")){
                                videoHappyElement.appendChild(doc.createTextNode(pathVideoHappy));
                            }
                            multimediaHappyElement.appendChild(videoHappyElement);
                            
                                // insert title attribute in video happy
                                Attr attr_title_video_happy = doc.createAttribute("title");
                                attr_title_video_happy.setValue(titleVideoHappy);
                                videoHappyElement.setAttributeNode(attr_title_video_happy);
                                
                                
                            // create videoElement for sad content
                            Element videoSadElement = doc.createElement("video");
                            if(!pathVideoSad.equals("")){
                                videoSadElement.appendChild(doc.createTextNode(pathVideoSad));
                            }
                            multimediaSadElement.appendChild(videoSadElement);
                            
                                // insert title attribute in video sad
                                Attr attr_title_video_sad = doc.createAttribute("title");
                                attr_title_video_sad.setValue(titleVideoSad);
                                videoSadElement.setAttributeNode(attr_title_video_sad);
                    
                }
                
                
            }
            
            
            
            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            DOMSource source = new DOMSource(doc);
            
            // controllo se file esiste già in pathXML e in caso affermativo lo cancella
            File fileXML = new File(pathXML);

            //verifica se la directory esiste
            if (!fileXML.exists()) {
                System.out.println(" universeServlet XML file does not exist.");
            } else {

                try {
                    delete(fileXML);
                } catch (Exception e) {
                }
            }
            
            
            StreamResult resultInFile = new StreamResult(new File(pathXML));
            StreamResult resultInResponse = new StreamResult(response.getWriter());
            
            

            // Output to console for testing
            // StreamResult result = new StreamResult(System.out);

            transformer.transform(source, resultInFile);
            transformer.transform(source, resultInResponse);
            
            System.out.println("File saved!");
            
            
            
        } catch (IOException ex) {
            Logger.getLogger(GetUniverseServlet.class.getName()).log(Level.SEVERE, null, ex);
        }catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
        
    }

    
    
    
    
    
    private static void delete(File file) throws IOException {

        if (file.isDirectory()) {

            //directory è vuota, quindi si può cancellare
            if (file.list().length == 0) {
                file.delete();
                System.out.println("Directory is deleted : " + file.getAbsolutePath());
            } else {

                //lista di tutte le sottodirectory contenute
                String files[] = file.list();

                for (String temp : files) {
                    //construttore file
                    File fileDelete = new File(file, temp);

                    //cancellazione ricorsiva
                    delete(fileDelete);
                }

                //controllo se directory è vuota e in caso affermativo la rimuovo
                if (file.list().length == 0) {
                    file.delete();
                    System.out.println("Directory is deleted : " + file.getAbsolutePath());
                }
            }

        } else {
            //se è file lo si cancella
            file.delete();
            System.out.println("File is deleted : " + file.getAbsolutePath());
        }
    }

}


